<template>
  <div class="app-container">
    <!-- 搜索头 -->
    <transition name="el-zoom-in-top">
      <el-form v-show="searchShow" :inline="true" label-width="80px">
        <el-form-item label="场景名称">
          <el-input v-model="listQuery.title" size="small" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="handleSearchClick">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="handleSearchCleanClick">清空</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <!-- 工具栏 -->
    <div class="tools-container">
      <div class="buttons">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddClick">新建</el-button>
      </div>
      <div class="tags">
        <el-button size="mini" icon="el-icon-search" circle @click="handleSearchShowChange" />
        <el-button size="mini" icon="el-icon-refresh" circle @click="handleRefreshClick" />
        <el-button size="mini" icon="el-icon-menu" circle @click="handleHeaderClick" />
      </div>
    </div>

    <!-- 表头 -->
    <el-dialog
      :visible.sync="headerShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="表头"
    >
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >全选</el-checkbox>
      <div style="margin: 15px 0;" />
      <el-checkbox-group v-model="header">
        <el-checkbox
          v-for="(value, key) in columns"
          :key="key"
          :label="key"
          :prop="key"
        >{{ value.label }}</el-checkbox>
      </el-checkbox-group>
    </el-dialog>

    <!-- 表格 -->
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      class="table-container"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      @sort-change="handleSortChange"
    >
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column
        v-for="(value, key) in columns"
        v-if="value.show"
        :key="key"
        :label="value.label"
        :align="value.center ? 'center' : 'left'"
        :prop="key"
        sortable
      />
      <el-table-column align="center" label="坐标">
        <template slot-scope="scope">
          <span>{{ `(${scope.row.x},${scope.row.y},${scope.row.z})` }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备偏角">
        <template slot-scope="scope">
          <span>{{ `(${scope.row.deflectionX},${scope.row.deflectionY},${scope.row.deflectionZ})` }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型">
        <template slot-scope="scope" sortable>
          <el-tag>{{ scope.row.type===1 ? '报警器' : scope.row.type===2 ? '固定点' : '测距点' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="绑定的场景" prop="sceneName" />
      <el-table-column align="center" label="ccid" prop="ccid" />
      <el-table-column align="center" label="流量(剩余/总量)" prop="ll" width="120" />
      <!-- <el-table-column align="center" label="设备状态" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="0 === scope.row.status" type="success">使用中</el-tag>
          <el-tag v-else type="danger">已关闭</el-tag>
        </template>
      </el-table-column>-->
      <!-- <el-table-column align="center" label="设备类型" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="0 === scope.row.type" type="danger">中控</el-tag>
          <el-tag v-else type="warning">点位</el-tag>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="在线状态" prop="online" width="80">
        <template slot-scope="scope">
          <el-tag v-if="0 === scope.row.online" type="success">在线</el-tag>
          <el-tag v-else type="danger">离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="电量状态" prop="online" width="80">
        <template slot-scope="scope">
          <el-tag v-if="1 === scope.row.batteryStatus" type="success">充电</el-tag>
          <el-tag v-else type="danger">未充电</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="clickMaintain(scope.row)"
          >{{ scope.row.isMain ? '开启维护' : '关闭维护' }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >升级版本号</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditClick(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteClick(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表单 -->
    <el-dialog
      :title="isCreate ? '新建记录' : '编辑记录'"
      :visible.sync="formShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleBeforeClose"
    >
      <el-form ref="form" :model="row" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="row.name" />
        </el-form-item>
        <el-form-item label="设备简称">
          <el-input v-model="row.alias" />
        </el-form-item>
        <!-- <el-form-item label="下发指令时间" v-if="row.type === 0">
          <el-input v-model="row.dinterval" />
        </el-form-item>
        <el-form-item label="补发次数" v-if="row.type === 0">
          <el-input v-model="row.reissue" />
        </el-form-item>
        <el-form-item label="下发指令超时时间" v-if="row.type === 0">
          <el-input v-model="row.reissueTimeout" />
        </el-form-item>
        <el-form-item label="允许设备处于非正常状态时间" v-if="row.type === 0">
          <el-input v-model="row.disnormalTimeout" />
        </el-form-item> -->
        <el-form-item label="设备硬件id">
          <el-input-number v-model="row.did" :disabled="!isCreate" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="row.type" placeholder="请选择">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="x">
          <el-input-number v-model="row.x" />
        </el-form-item>
        <el-form-item label="y">
          <el-input-number v-model="row.y" />
        </el-form-item>
        <el-form-item label="z">
          <el-input-number v-model="row.z" />
        </el-form-item>
        <el-form-item label="航向角">
          <el-input-number v-model="row.deflectionX" />
        </el-form-item>
        <el-form-item label="俯仰角">
          <el-input-number v-model="row.deflectionY" />
        </el-form-item>
        <el-form-item label="翻滚角">
          <el-input-number v-model="row.deflectionZ" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBeforeClose">取 消</el-button>
        <el-button v-if="isCreate" type="primary" @click="handleCreateClick">创 建</el-button>
        <el-button v-else type="primary" @click="handleUpdateClick">更 新</el-button>
      </div>
    </el-dialog>
    <!-- 分页 组件 -->
    <el-pagination
      :current-page.sync="listQuery.page"
      :page-size="listQuery.size"
      :total="total"
      :page-sizes="[5,10,20,30,50]"
      class="pagination-container"
      background
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 升级 -->
    <el-dialog title="升级版本号" :visible.sync="firmwareShow" width="30%">
      <el-form ref="versionForm" :model="versionForm" label-width="100px" :rules="rule">
        <el-form-item label="版本号" prop="fid">
          <el-select v-model="versionForm.fid" placeholder="请选择">
            <el-option
              v-for="item in firmwareList"
              :key="item.id"
              :label="item.version + '/' + item.remark || ''"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="firmwareShow = false">取 消</el-button>
        <el-button type="primary" @click="handleClickUpdate('versionForm')">升 级</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, del, update, add, versionUpdate, columns } from '@/api/device'
import { maintain } from '@/api/dashboard'
import { getFirmwareList } from '@/api/firmware'
import { toLowerCase } from '@/utils'
import { check } from '@/utils/check'
import { mapGetters } from 'vuex'

export default {
  filters: {
    onlineFilter: function(value) {
      const map = ['在线', '离线']
      return map[value]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        order: 'id',
        title: ''
      },
      total: 0,
      searchShow: false,
      formShow: false,
      isCreate: true, // true创建, false:更新
      headerShow: false,
      isIndeterminate: true,
      checkAll: true,
      columns: [],
      row: {},
      firmwareList: [],
      versionForm: {
        deviceId: '',
        fid: ''
      },
      rule: {
        fid: [{ required: true, message: '请选择版本', trigger: 'change' }]
      },
      firmwareShow: false,
      checkAdd: false,
      checkEdit: false,
      checkDelete: false,
      typeOptions: [
        {
          value: 0,
          label: '测距点'
        },
        {
          value: 1,
          label: '报警器'
        },
        {
          value: 2,
          label: '固定点'
        }
      ]

    }
  },
  computed: {
    // ...mapGetters([
    //   'roles'
    // ]),
    header: {
      set: function(v) {
        Object.keys(this.columns).forEach(key => {
          this.columns[key].show = false
          v.forEach(i => {
            if (key === i) {
              this.columns[key].show = true
            }
          })
        })
        const checkedCount = v.length
        this.checkAll = checkedCount === Object.keys(this.columns).length
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < Object.keys(this.columns).length
        return Object.keys(this.columns).filter(i => this.columns[i].show)
      },
      get: function() {
        var array = Object.keys(this.columns).filter(i => this.columns[i].show)
        return array
      }
    }
  },
  mounted() {
    // check(this.roles, ['激活设备', '编辑设备', '删除设备'], (list) => {
    //   this.checkAdd = list[0]
    //   this.checkEdit = list[1]
    //   this.checkDelete = list[2]
    // })
    this.fetchData()
    this.columns = columns()
    var checkedCount = this.header.length
    this.checkAll = checkedCount === Object.keys(this.columns).length
    this.isIndeterminate =
      checkedCount > 0 && checkedCount < Object.keys(this.columns).length
  },
  methods: {
    fetchData() {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data.records.map(item => {
          const ccidData = item.ccidData ? item.ccidData === 'Error request, response status: 405' ? '' : JSON.parse(item.ccidData) : ''
          return {
            ...item,
            ll: ccidData
              ? ccidData.status === '0'
                ? `${ccidData.data.left_flow} || ${ccidData.data.total_flow}`
                : ''
              : ''
          }
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },

    // <<<< 搜索头
    handleSearchClick() {
      if (!this.listQuery.title) {
        this.$message({
          message: '搜索内容不能为空',
          type: 'error',
          duration: 800
        })
      }
    },
    handleSearchCleanClick() {
      this.listQuery.title = ''
    },
    // >>>> 搜索头

    // <<<< 工具栏相关
    handleCheckAllChange(val) {
      this.header = val ? Object.keys(this.columns) : []
      Object.keys(this.columns).forEach(key => {
        this.columns[key].show = val
      })
      this.isIndeterminate = false
    },
    handleRefreshClick() {
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 800
      })
      this.fetchData()
    },
    handleSearchShowChange() {
      this.searchShow = !this.searchShow
    },
    handleAddClick() {
      this.isCreate = true
      this.formShow = true
      this.row = {
        deflectionX: 0,
        deflectionY: 0,
        deflectionZ: 0
      }
    },
    // 升级版本
    handleUpdate(data) {
      getFirmwareList({ deviceId: data.id }).then(res => {
        if (res.ok) {
          this.firmwareList = res.data
        }
      })
      this.versionForm = {
        deviceId: data.id,
        fid: data.fid
      }
      this.firmwareShow = true
    },
    handleClickUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const { deviceId, fid } = this.versionForm
          versionUpdate({
            deviceId,
            fid
          }).then(res => {
            if (res.ok) {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 800
              })
              this.firmwareShow = false
              this.fetchData()
            }
          })
        }
      })
    },
    // 维护模式的开启与关闭 1 关闭状态 0 开启状态
    clickMaintain(data) {
      maintain({
        deviceId: data.id,
        status: data.isMain ? 0 : 1
      }).then(res => {
        if (res.ok) {
          this.$message({
            type: 'success',
            message: res.data
          })
          this.fetchData()
        }
      })
    },
    // >>>> 工具栏相关

    // <<<< 表头相关

    // >>>> 表头相关

    // <<<< 表格相关
    handleDeleteClick(row) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row.id).then(res => {
            this.fetchData()
          })
        })
        .catch(() => {
          console.log('取消删除')
        })
    },
    handleEditClick(row) {
      this.isCreate = false
      this.formShow = true
      this.row = Object.assign({}, row)
    },
    handleBeforeClose() {
      this.row = {}
      this.formShow = false
      this.$refs.form.resetFields()
    },
    // >>>> 表格相关

    // <<<< 分页相关
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleSortChange(val) {
      this.listQuery.asc = val.order !== 'descending'
      this.listQuery.order = toLowerCase(val.prop)
      this.fetchData()
    },
    handleHeaderClick() {
      this.headerShow = true
    },
    // >>>> 分页相关

    // <<<< 表单相关
    handleCreateClick() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.row.x = this.row.x ? this.row.x : 0
          this.row.y = this.row.y ? this.row.y : 0
          this.row.z = this.row.z ? this.row.z : 0
          add(this.row).then(res => {
            this.$message({
              message: res.data,
              type: 'success',
              duration: 800
            })
            this.fetchData()
            this.formShow = false
            this.form = {}
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleUpdateClick() {
      this.$refs.form.validate(valid => {
        if (valid) {
          update(this.row).then(res => {
            this.fetchData()
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 800
            })
            this.formShow = false
            this.form = {}
          })
        }
      })
    }
    // >>>> 表单相关

    // <<<<< 其他业务
    // >>>>> 其他业务
  }
}
</script>
